package com.talkyun.openx.server.timer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Timer;
import java.util.TimerTask;

public class RearGuardTimer {
    private static final Logger logger = LoggerFactory.getLogger(RearGuardTimer.class);

    private abstract static class SafeTask extends TimerTask {
        @Override
        public void run() {
            try {
                doTask();
            } catch (Throwable t) {
                logger.error("Fail in timer!", t);
                RearGuardTimer.sleep(3 * 1000);
            }
        }

        abstract void doTask();
    }

    private Timer timer = new Timer("openx-guard", true);

    public RearGuardTimer startup() {
        logger.info("Startup OpenX timer...");
        return this;
    }

    public void shutdown() {
        timer.cancel();
        logger.info("Shutdown OpenX timer!");
    }

    public void addTask(final Runnable task, final long period) {
        timer.schedule(new SafeTask() {
            @Override
            public void doTask() {
                task.run();
            }
        }, 0, period);
    }

    private static void sleep(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            // ignore
        }
    }
}